## Cross Employer Wage Elasticity Estimates

## 

#CHOOSE sample size
sample_choice <- "10_percent_sample"

#CHOOSE balance requirement of the panel ("choice can be: unbalanced", "pre_post_1_t" or "pre_post_3_t")
suffix_mild_balanced = "pre_post_3_t"

#Define directory to save the tex tables
output_tables_dir <- file.path(getwd(), "output/")

#-----------------------------------------------------------#
#Load dataset
df <- readRDS(paste0("data/derived/mild_balanced_", suffix_mild_balanced,"_stacked_nonpolicy_firm_payroll_provider_dataset_", sample_choice, ".rds"))

df <- df %>% 
  mutate(super_gap_std = as.vector(scale(super_gap)),
         T_std = as.vector(scale(T)))

df <- df %>%
  mutate(cz = czone)

## Load the stacked_policy_firm_wages_data 

stacked_policy_firm_wages_data <- read.csv("data/credit_bureau/stacked_policy_firm_wages_dataset.csv")

#### Merge the Data 
df_merge <- left_join(df, stacked_policy_firm_wages_data, by = c("cz", "etime", "trt_exp"))

#-----------------------------------------------------------#


#Create post_period dummy
df_merge = df_merge %>% 
  mutate(post_period24 = ifelse(etime > -1, 1, 0))

df_merge = df_merge %>% 
  mutate(post_period12 = case_when(
    etime >= 0 & etime <= 6 ~ 1, 
    etime <= -1 & etime >= -6 ~ 0, 
    TRUE ~ NA_real_
  ))

#period_var = c("post_period", "post_period12")
period_var = c("post_period12")
#Define set of outcome variables of interest
policy_var = c("ln_wage_policy")

y = c("ln_avg_wage_exact") #, "ln_avg_wage_exact_wins_1_99")
iv_var = c("ln_wage_policy")

#Define set of treatment variables of interest
treat_var_vector = c("T_std", "super_gap_std")

############################ CHANGE DATA SAMPLES ################

df2 = df_merge %>% 
  filter(share_affected > .3) 

df3 = df_merge %>% 
  filter(mw == 15) 

####################### Regressions #################### 

for(p in period_var){
  
  for(t in treat_var_vector){
    
    #Set the according variable for the unstandardized treatment variable
    unst_t = substr(t, start = 1, stop = nchar(t) - 4)
    
    #Set a dictionary for variables' names
    dict = c(ln_avg_wage_exact = "Log Average Wage",
             ln_wage_policy = "Cross Wage Elasticity",
             T_std = "Large Retailer Gap (std.)",
             super_gap_std = "Market Gap (std.)",
             #post_period = "Post",
             clt_client = "Firm",
             czone = "CZ",
             etime = "Event time",
             trt_exp = "")
    
    fixest::setFixest_dict(dict)
    
    #Define formula for regression (this is necessary to loop over different dependent variables)
    formula1a = as.formula(paste(y, "~ ", t, "*", p,  "| 
                              clt_client^trt_exp + czone^trt_exp + etime^trt_exp"))
    
    formula1b = as.formula(paste(policy_var, "~ ", t, "*", p, "| 
                             clt_client^trt_exp + czone^trt_exp + etime^trt_exp"))
    
    formula2 = as.formula(paste(y, "~", 1, "| clt_client^trt_exp + czone^trt_exp + etime^trt_exp |", 
                                iv_var, "~", t, "*", p))
    
    #---------------------#
    ### Specification 1 ###
    #---------------------#
    fit1a = fixest::feols(formula1a, cluster = ~czone, data = df_merge)
    fit1b = fixest::feols(formula1b, cluster = ~czone, data = df_merge)
    iv_fit1 = fixest::feols(formula2, cluster = ~czone, data = df_merge)
    
    
    #---------------------#
    ### Specification 2 ###
    #---------------------#
    fit2a = fixest::feols(formula1a, cluster = ~czone, data = df2)
    fit2b = fixest::feols(formula1b, cluster = ~czone, data = df2)
    iv_fit2 = fixest::feols(formula2, cluster = ~czone, data = df2)
    
    
    #---------------------#
    ### Specification 3 ###
    #---------------------#
    fit3a = fixest::feols(formula1a, cluster = ~czone, data = df3)
    fit3b = fixest::feols(formula1b, cluster = ~czone, data = df3)
    iv_fit3 = fixest::feols(formula2, cluster = ~czone, data = df3)
    
    # models <- list( fit1, IV = iv_fit1),
    #   Model2 <- list(OLS = fit2, IV = iv_fit2),
    #   Model3 <- list(OLS = fit3, IV = iv_fit3)
    # )
    
    
    sd_unst_t_pre1 = df_merge[fixest::obs(fit1a), ] %>% 
      summarise(sd = sd(!!sym(unst_t))) %>%
      pull()
    
    sd_unst_t_pre2 = df2[fixest::obs(fit2a), ] %>% 
      summarise(sd = sd(!!sym(unst_t))) %>%
      pull()
    
    sd_unst_t_pre3 = df3[fixest::obs(fit3a), ] %>% 
      summarise(sd = sd(!!sym(unst_t))) %>%
      pull()
    
    cz_count1 <- n_distinct(df_merge$czone)
    
    cz_count2 <- n_distinct(df2$czone)
    
    cz_count3 <- n_distinct(df3$czone)
    
    clt_client_count1 <- length(unique(df_merge$clt_client))
    
    clt_client_count2 <- length(unique(df2$clt_client))
    
    clt_client_count3 <- length(unique(df3$clt_client))
    
    table_style <- fixest::style.tex(main = "aer",
                                     model.format = "",
                                     model.title = "\\textit{OLS Dep. var: Log Average Wage}",
                                     yesNo = "Y",
                                     depvar.title = "Dep. var:",
                                     depvar.style = "*", #italic dependent variable title
                                     fixef.title = "\\midrule",
                                     fixef.suffix = "FEs",
                                     fixef.where = "var",
                                     line.top = "double"
    )
    
    #Output customized TEX table
    fixest::etable(fit1a, fit2a, fit3a, 
                   tex = T,
                   style.tex = table_style,
                   depvar = F, #remove dependent variable title from the top part of the table
                   headers = c("All VMWs", "Major VMWs", "$15 VMWs"),
                   fitstat = ~ n,
                   #group = c("OLS", "IV"),
                   file = file.path(
                     output_tables_dir,
                     paste0("avgwage_OLS", suffix_mild_balanced, "_", sample_choice, y, "_treat_var_", t, p, ".tex")
                   ),
                   replace = TRUE,
                   extralines = list( "CZ's" = c(cz_count1, cz_count2, cz_count3),
                                      "Number of Firms" = c(clt_client_count1, clt_client_count2, clt_client_count3),
                                      "SD treat. var. (unstd.)" = c(sd_unst_t_pre1, sd_unst_t_pre2, sd_unst_t_pre3))
                   #model.order
    )
    
    table_style <- fixest::style.tex(main = "aer",
                                     model.format = "",
                                     model.title = "\\textit{OLS Dep. var: Cross Wage Elasticity}",
                                     yesNo = "Y",
                                     depvar.title = "Dep. var:",
                                     depvar.style = "*", #italic dependent variable title
                                     fixef.title = "\\midrule",
                                     fixef.suffix = "FEs",
                                     fixef.where = "var",
                                     line.top = "double"
    )
    
    #Output customized TEX table
    fixest::etable(fit1b, fit2b, fit3b,
                   tex = T,
                   style.tex = table_style,
                   depvar = F, #remove dependent variable title from the top part of the table
                   headers = c("All VMWs", "Major VMWs", "$15 VMWs"),
                   fitstat = ~ n,
                   #group = c("OLS", "IV"),
                   file = file.path(
                     output_tables_dir,
                     paste0("cross_wage_elasticity_OLS", suffix_mild_balanced, "_", sample_choice, y, "_treat_var_", t,p, ".tex")
                   ),
                   replace = TRUE,
                   extralines = list("CZ's" = c(cz_count1, cz_count2, cz_count3),
                                     "Number of Firms" = c(clt_client_count1, clt_client_count2, clt_client_count3),
                                     "SD treat. var. (unstd.)" = c(sd_unst_t_pre1, sd_unst_t_pre2, sd_unst_t_pre3))
                   #model.order
    )
    
    table_style <- fixest::style.tex(main = "aer",
                                     model.format = "",
                                     model.title = "\\textit{IV Dep. Var: Log Average Wage}",
                                     yesNo = "Y",
                                     depvar.title = "Dep. var:",
                                     depvar.style = "*", #italic dependent variable title
                                     fixef.title = "\\midrule",
                                     fixef.suffix = "FEs",
                                     fixef.where = "var",
                                     line.top = "double"
    )
    
    #Output customized TEX table
    fixest::etable(iv_fit1, iv_fit2, iv_fit3, 
                   tex = T,
                   style.tex = table_style,
                   depvar = F, #remove dependent variable title from the top part of the table
                   headers = c("All VMWs", "Major VMWs", "$15 VMWs"),
                   fitstat = ~ n,
                   #group = c("OLS", "IV"),
                   file = file.path(
                     output_tables_dir,
                     paste0("cross_wage_elasticity_IV", suffix_mild_balanced, "_", sample_choice, y, "_treat_var_", t,p, ".tex")
                   ),
                   replace = TRUE,
                   extralines = list("CZ's" = c(cz_count1, cz_count2, cz_count3),
                                     "Number of Firms" = c(clt_client_count1, clt_client_count2, clt_client_count3),
                                     "SD treat. var. (unstd.)" = c(sd_unst_t_pre1, sd_unst_t_pre2, sd_unst_t_pre3))
                   
    )
    
    
    
  }
  
  
}



